﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Input;
using System.Windows.Controls;

namespace LayoutWindow.Behaviors
{
    public class TreeSelect:DependencyObject
    {
        public static ICommand GetCommand(DependencyObject obj)
        {
            return (ICommand)obj.GetValue(CommandProperty);
        }

        public static void SetCommand(DependencyObject obj, ICommand value)
        {
            obj.SetValue(CommandProperty, value);
        }
        public static readonly DependencyProperty CommandProperty =
            DependencyProperty.RegisterAttached("Command", typeof(ICommand), typeof(TreeSelect),
            new PropertyMetadata(OnSetCommandCallback));

        public static object GetCommandParameter(DependencyObject obj)
        {
            return (object)obj.GetValue(CommandParameterProperty);
        }

        public static void SetCommandParameter(DependencyObject obj, object value)
        {
            obj.SetValue(CommandParameterProperty, value);
        }
        public static readonly DependencyProperty CommandParameterProperty =
            DependencyProperty.RegisterAttached("CommandParameter", typeof(object), typeof(TreeSelect),
            new PropertyMetadata(OnSetCommandParameterCallback));
        
        
        private static readonly DependencyProperty TreeSelectCommandBehaviorProperty =
            DependencyProperty.RegisterAttached("TreeSelectCommandBehavior",
            typeof(TreeSelectCommandBehavior),typeof(TreeSelect), null);

        private static void OnSetCommandCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
        {
            TreeView tree = dependencyObject as TreeView;
            if (tree != null)
            {
                TreeSelectCommandBehavior behavior = GetOrCreateBehavior(tree);
                behavior.Command = e.NewValue as ICommand;
            }
        }
        private static void OnSetCommandParameterCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
        {
            TreeView tree = dependencyObject as TreeView;
            if (tree != null)
            {
                TreeSelectCommandBehavior behavior = GetOrCreateBehavior(tree);
                behavior.CommandParameter = e.NewValue;
            }
        }
        private static TreeSelectCommandBehavior GetOrCreateBehavior(TreeView tree)
        {
            TreeSelectCommandBehavior behavior =
            tree.GetValue(TreeSelectCommandBehaviorProperty) as TreeSelectCommandBehavior;
            if (behavior == null)
            {
                behavior = new TreeSelectCommandBehavior(tree);
                tree.SetValue(TreeSelectCommandBehaviorProperty, behavior);
            }
            return behavior;
        }
    }
}
